package cn.wtg.kotlinlib.net.downloadAndUpload.upload

import android.util.Log
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*
import java.io.IOException

/**
 * author: wtg
 * date:2020/5/25 0025
 * desc: 上传带进度的requestBody
 */
class UploadRequestBody(requestBody: RequestBody, loadingListener: LoadingListener) :
    RequestBody() {
    private val mRequestBody: RequestBody
    private val mLoadingListener: LoadingListener
    private var mContentLength: Long = 0

    init {
        mRequestBody = requestBody
        mLoadingListener = loadingListener
    }

    override fun contentType(): MediaType? {
        return mRequestBody.contentType()
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        val byteSink = ByteSink(sink)
        val mBufferedSink: BufferedSink = byteSink.buffer()
        mRequestBody.writeTo(mBufferedSink)
        mBufferedSink.flush()
    }

    //文件的总长度
    override fun contentLength(): Long {
        try {
            if (mContentLength == 0L) mContentLength = mRequestBody.contentLength()
            return mContentLength
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return -1
    }

    private inner class ByteSink internal constructor(delegate: Sink?) : ForwardingSink(delegate!!) {
        //已经上传的长度
        private var mByteLength = 0L
        @Throws(IOException::class)
        override fun write(source: Buffer, byteCount: Long) {
            super.write(source, byteCount)
            mByteLength += byteCount
            Log.e("wirite", "$mByteLength---")
            mLoadingListener.onProgress(mByteLength, contentLength())
        }
    }

    /**
     * 上传监听
     */
    interface LoadingListener {
        fun onProgress(currentLength: Long, contentLength: Long)
    }
}